﻿using System;
using System.Web.UI.WebControls;
using Cosmetic.DataEntity;
using Cosmetic.Logic;

public partial class Controls_BrandDropDownList : System.Web.UI.UserControl
{
	private BrandManager m_BrandManager	= new BrandManager();
	public delegate void SelectedBrandChangedHandler(Brand aBrand);
	public event SelectedBrandChangedHandler SelectedBrandChanged;


	protected void Page_Load(object sender, EventArgs e)
	{
		this.ddlBrand.AutoPostBack	= (null != this.SelectedBrandChanged);

		if (!IsPostBack)
		{
			this.BindBrand();
		}
	}

	public Brand SelectedBrand
	{
		get
		{
			if (this.ddlBrand.Enabled == true)
			{
				return this.m_BrandManager.GetBrandById(new Guid(this.ddlBrand.SelectedValue));
			}
			return null;
		}
		set
		{
			this.BindBrand();
			this.ddlBrand.SelectedIndex		= this.ddlBrand.Items.IndexOf(this.ddlBrand.Items.FindByValue(value.BrandId.ToString()));
		}
	}

	protected void ddlBrand_SelectedIndexChanged(object sender, EventArgs e)
	{
		if (null != this.SelectedBrandChanged)
		{
			this.SelectedBrandChanged(this.m_BrandManager.GetBrandById(new Guid(this.ddlBrand.SelectedValue)));
		}
	}

	private void BindBrand()
	{
		this.ddlBrand.Items.Clear();

		this.ddlBrand.DataSource		= this.m_BrandManager.GetAll();
		this.ddlBrand.DataTextField		= "Name";
		this.ddlBrand.DataValueField	= "BrandId";
		this.ddlBrand.DataBind();

		if (this.ddlBrand.Items.Count > 0)
		{
			this.ddlBrand.Enabled	= true;
			this.ddlBrand_SelectedIndexChanged(null, null);
		}
		else
		{
			this.AddNoDataItemToDropDownList(ddlBrand);
		}
	}

	public void Refresh()
	{
		this.BindBrand();
	}

	private void AddNoDataItemToDropDownList(DropDownList aDropDownList)
	{
		aDropDownList.Items.Add(new ListItem("No Data", string.Empty));
		aDropDownList.SelectedIndex		= 0;
		aDropDownList.Enabled			= false;
	}

}
